package com.browsesoft.htmlcomponent;

import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.browsesoft.ExtendElement;
import com.browsesoft.ManagerGroup;
import com.browsesoft.dbtools.DBTools;

public class HTMLMainDocPageTableShowModel extends
		com.browsesoft.htmlcomponent.HTMLDBTableModel {
	/**
	 * 初始化model
	 */
	public void init(HttpServletRequest request) throws Exception {
		// 得到模板中的form元素中的form属性值，用来
		form = this.component.getElement().getAttribute("form");
		// 如果form属性值存在
		if (form != null && !form.equals("")) {
			// 得到模板管理嚣
			TemplateManager manager = (TemplateManager) ManagerGroup
					.getManagerGroup().getManager("template");
			// 由form属性值生成页面
			Template t = manager.getTemplateByName(form);
			// 得到模板文档,
			Document document = t.getDocument();
			// 解析文档,找出需要处理的根元素
			Element root = (Element) document.getElementsByTagName("body")
					.item(0);
			// 找到所有显示的组件
			LinkedList v = ExtendElement.findElements(root, "show", "show");
			// 生成SQL语句
			sql = "select *";
			for (int i = 0; i < v.size(); i++) {
				Element element = (Element) v.get(i);
				enames.add(element.getAttribute("name"));
				cnames.add(element.getAttribute("cname"));
			}
			// 找到数据库表名
			tableName = ((Element) document.getElementsByTagName("form")
					.item(0)).getAttribute("name");
			sql += " from " + tableName;
		}
	}

	/**
	 * 得到列数
	 * 
	 * @return 列数
	 */
	public int getColumnCount() {
		return cnames.size();
	}

	/**
	 * 修改单元值
	 */
	public void modifyCellValue(Element td, Document doc, int row, int col) {
		try {
			int IDindex = DBTools.indexOf(datas[0], "id");
			// 显示文档名字，并加链接
			if (col == 0) {
				if (this.getsort() && this.getOrderBy()) {
					this.sort(this.getsortname());
				} else if (this.getsort() && !this.getOrderBy()) {
					this.reverseSort(this.getsortname());
				}
				Element e = (Element) ExtendElement.findElements(td, "type",
						"docLink").get(0);
				String s = e.getAttribute("href");
				s = s.replaceAll("id=", "id=" + datas[row + 1][IDindex]);
				e.setAttribute("href", s);
				int index = DBTools.indexOf(datas[0], (String) enames.get(col));
				if (index != -1) {
					e.appendChild(doc.createTextNode(datas[row + 1][index]));
				} else {
					e.appendChild(doc.createTextNode(""));
				}
				td.appendChild(e);
			} else if (col < cnames.size() && col != 0) {
				if (this.getsort() && this.getOrderBy()) {
					this.sort(this.getsortname());
				} else if (this.getsort() && !this.getOrderBy()) {
					this.reverseSort(this.getsortname());
				}
				Element e = (Element) ExtendElement.findElements(td, "type",
						"docLink").get(0);
				td.removeChild(e);
				int index = DBTools.indexOf(datas[0], (String) enames.get(col));
				if (index != -1) {
					td.appendChild(doc.createTextNode(datas[row + 1][index]));
				} else {
					td.appendChild(doc.createTextNode(""));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
